import { defineStore } from 'pinia'
import { getMenuRouter } from '@/api/loginApi'
import router, { dynamicRoutes, resetRouter } from '@/router'
import userUserStore from '@/store/user'

function generateNameMap(menus) {
    const nameMap = {}
    menus.forEach(menu => {
        handleMenu(menu, nameMap, [])
    })
    return nameMap
}

function handleMenu(menu, nameMap, titleArr) {
    titleArr.push(menu.title)
    nameMap[menu.name] = JSON.parse(JSON.stringify(titleArr))
    if (menu.children && menu.children.length > 0) {
        menu.children.forEach(menu => {
            let newTitleArr = JSON.parse(JSON.stringify(titleArr))
            handleMenu(menu, nameMap, newTitleArr)
        })
    }
}

export default defineStore('menu', {
    state: () => {
        return {
            routesMenusLoaded: false, // 路由菜单是否已加载
            menus: [], // 菜单
            routes: [], // 路由,
            perms: [], // 权限
        }
    },
    getters: {

    },
    actions: {
        loadRoutesMenus() {
            return new Promise(async (resolve, reject) => {
                try {
                    let userStore = userUserStore()
                    // console.log('userStore', userStore, userStore.userInfo, !userStore.userInfo);

                    if (!userStore.userInfo) {
                        // console.log('---');
                        await userStore.getUserInfo()
                    }
                    let menuRouter = await getMenuRouter()
                    let menus = menuRouter.menuDTOs
                    let routes = menuRouter.routerDTOs
                    let perms = menuRouter.btnDtos

                    // 保存路由
                    this.routes = routes

                    // 保存菜单
                    this.menus = menus
                    // console.log('menus', this.menus)

                    // 保存权限
                    this.perms = perms

                    // debugger
                    const nameMap = generateNameMap(menus)

                    //定义一个函数，引入所有views下.vue文件
                    const modules = import.meta.glob(`@/views/**/*.vue`);
                    // console.log(modules,'modules');
                    /*
                        /src/views/404/NotFound.vue: () => import("/src/views/404/NotFound.vue")
                        /src/views/Home.vue: () => import("/src/views/Home.vue")
                        /src/views/login/index.vue: () => import("/src/views/login/index.vue?t=1682323488070")
                        /src/views/sys/Menu.vue: () => import("/src/views/sys/Menu.vue")
                        /src/views/sys/Role.vue: () => import("/src/views/sys/Role.vue")
                        /src/views/sys/User.vue: () => import("/src/views/sys/User.vue")
                        /src/views/test/test2/test_2_1.vue: () => import("/src/views/test/test2/test_2_1.vue")
                        /src/views/test/test2/test_2_2.vue: () => import("/src/views/test/test2/test_2_2.vue")
                        /src/views/test/test_1.vue: () => import("/src/views/test/test_1.vue")
                    */

                    // 动态加载路由
                    routes.forEach(route => {
                        // debugger
                        // console.log(route.componentPath);
                        // console.log(route.componentPath, route.componentPath.replace('@','/src'),modules[route.componentPath.replace('@','/src')]);
                        router.addRoute(
                            'layout',
                            {
                                path: route.accessPath,
                                name: route.routerName,
                                meta: {
                                    titleArr: nameMap[route.routerName],
                                    title: nameMap[route.routerName][nameMap[route.routerName].length - 1]
                                },

                                // 改成使用import.meta.glob动态导入
                                component: modules[route.componentPath.replace('@', '/src')]
                            }
                        )
                    })

                    
            

                    router.addRoute({
                        path: '/:pathMatch(.*)*',
                        name: 'notFound',
                        component: () => import('../views/404/NotFound.vue')
                    })


                    // 添加动态路由(先省略校验权限)
                    /* dynamicRoutes.forEach(dynamicRoute => router.addRoute(dynamicRoute))
                    console.log(dynamicRoutes,'dynamic routes'); */

                    // console.log(router.getRoutes(),'加载路由 finished');
                    this.routesMenusLoaded = true

                    resolve()

                } catch (err) {
                    reject(err)
                }

            })
        },
        // 用户退出登录后, 还需要清空菜单/路由等信息    
        clearMenuRouterInfo() {
            resetRouter()
            this.menus = []
            this.perms = []
            this.routes = []
            this.routesMenusLoaded = false
        }
    }
})
